//
//  WmcTeamCloudAlbumHomeVC.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import MJRefresh
import UIKit
import YPBedrock
import SVProgressHUD

// MARK: - 扩展WmcTeamCloudAlbumHomeVC + WmcVMProtocol

extension WmcTeamCloudAlbumHomeVC: WmcVMProtocol {
    typealias VMType = WmcTeamCloudAlbumHomeVM
}

// MARK: - [WmcTeamCloudAlbumHomeVC]

class WmcTeamCloudAlbumHomeVC: WmcBaseVC {
    /// 执行次数
    var excuteCount: Int = 0
    /// 是否已经显示过示例视图
    var isShowedExampleView: Bool = false
    /// 第一页是否有数据
    var isFirstPageHasData: Bool = false

    override func backAction() {
        if isShowedExampleView {
            WmcUserdefault.save(value: true, forKey: .Tips.Home.showAblumExampleView)
        }
        popVC()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        WmcUserdefault.save(value: false, forKey: .Tips.Home.isPopedTeamAlbumHomePage)
        /// 获取列表数据
        getData()

        WmcNotificationManager.shared.addObserver(type: .editTeamRemarkSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .editTeamNameSucceed) { [weak self] noti in
            guard let dic = noti.object as? [String: Any], let weakSelf = self, let teamName = dic["teamName"] as? String else { return }
            // 更新名字
            weakSelf.currentTitleLabel.text = teamName
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .editUserAvatarSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .deletePhotoSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .editUserNameSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
    }

    override func makeUI() {
        title = viewModel.title
        makeNavView(style: .white, showShadow: false)
        // 添加导航栏细线
        addNaviLineView()
        navView.titleLabel.isHidden = true
        navView.addSubview(currentTitleLabel)

        currentTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(Wmc_statusBarHeight)
            make.bottom.right.equalToSuperview()
            make.left.equalTo(Wmc_standardEdge.left + 23).offset(40)
            make.right.equalTo(-90)
        }
        currentTitleLabel.text = viewModel.title

        view.addSubview(filterView)
        view.addSubview(tableView)
        view.addSubview(topButton)

        navView.addSubview(inviteMemberButton)
        inviteMemberButton.snp.makeConstraints { make in
            make.centerY.equalTo(navView.backImageView)
            make.right.equalTo(-Wmc_standardEdge.right)
        }

        filterView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
        }

        tableView.snp.makeConstraints { make in
            make.top.equalTo(filterView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }

        topButton.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.bottom.equalTo(-16)
            make.width.height.equalTo(60)
        }
    }

    override func bindViewModel() {
        viewModel.listData.skip(1).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.tableView.wmcReloadData()
            weakSelf.netErrorView.removeFromSuperview()
        }.disposed(by: rx.disposeBag)
        
        viewModel.error.bind {[weak self] error in
            guard let weakSelf = self,let _ = error else { return }
            weakSelf.addSubview(weakSelf.netErrorView)
            weakSelf.netErrorView.snp.makeConstraints { make in
                make.top.left.right.bottom.equalTo(weakSelf.tableView)
            }
        }.disposed(by: rx.disposeBag)

        let topShowHeight = (Wmc_screenHeight - Self.NavHeight - 64 - Wmc_safeAreaTop - Wmc_safeAreaBottom - 50) * 1.5
        tableView.rx.contentOffset.map { $0.y < topShowHeight }.bind(to: topButton.rx.isHidden).disposed(by: rx.disposeBag)
    }

    override func bindViewAction() {
        /// 邀请
        inviteMemberButton.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in
            guard let weakSelf = self, let team = weakSelf.viewModel.teamAblum else { return }
            weakSelf.viewModel.getSelfMember { selfMember in
                let vm = WmcTeamCloudInviteMemberVM()
                vm.teamAblum = team
                vm.teamMember = selfMember
                // 标记当前跳转，以便后续回到次位置
                weakSelf.popToVCMark = true
                WmcNavigatorManager.push(.inviewTeamMember, parms: vm)?.hidesBottomBarWhenPushed = true
            }
        }.disposed(by: rx.disposeBag)

        /// 搜索
        filterView.searchBtn.rx.controlEvent(.touchUpInside).subscribe { [weak self] _ in
            guard let weakSelf = self else { return }
            let vm = WmcTeamSearchVM()
            vm.teamAblum = weakSelf.viewModel.teamAblum
            WmcNavigatorManager.push(.teamAlbumSearch, parms: vm)?.hidesBottomBarWhenPushed = true
        }.disposed(by: rx.disposeBag)

        /// 选择日期
        filterView.rx.tapGesture().skip(1).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.showCalendar = true
            weakSelf.viewModel.fetchPhotoCalendarList { _, dates in
                weakSelf.showCalendarView(dataList: dates)
            }
        }.disposed(by: rx.disposeBag)

        // 去拍照
        emptyView.takePhotoBtn.rx.controlEvent(.touchUpInside).bind {
            /// 先去除 团队tab 导航栏栈上
            WmcNotificationManager.shared.post(type: .clickedGotoShoot, object: nil)
        }.disposed(by: rx.disposeBag)

        emptyView.inviteMemebrTakePhoto.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self, let team = weakSelf.viewModel.teamAblum else { return }
            weakSelf.viewModel.getSelfMember { selfMember in
                let vm = WmcTeamCloudInviteMemberVM()
                vm.teamAblum = team
                vm.teamMember = selfMember
                WmcNavigatorManager.push(.inviewTeamMember, parms: vm)?.hidesBottomBarWhenPushed = true
            }
        }.disposed(by: rx.disposeBag)

        // 去拍照
        exmapleView.takePhotoBtn.rx.controlEvent(.touchUpInside).bind {
            /// 先去除 团队tab 导航栏栈上
            WmcNotificationManager.shared.post(type: .clickedGotoShoot, object: nil)
        }.disposed(by: rx.disposeBag)

        exmapleView.inviteMemebrTakePhoto.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self, let team = weakSelf.viewModel.teamAblum else { return }
            weakSelf.viewModel.getSelfMember { selfMember in
                let vm = WmcTeamCloudInviteMemberVM()
                vm.teamAblum = team
                vm.teamMember = selfMember
                WmcNavigatorManager.push(.inviewTeamMember, parms: vm)?.hidesBottomBarWhenPushed = true
            }
        }.disposed(by: rx.disposeBag)
    }

    /// 获取数据
    /// - Returns: description
    func getData() {
        viewModel.fetchPhotoCalendarList { [weak self] recenDate, _ in
            guard let weakSelf = self else { return }
            if let recent = recenDate {
                // 选了日期
                weakSelf.viewModel.fetchTeamResource(date: recent.date)
                weakSelf.updateFilterViewUI(model: recent)
            } else {
                // 未选择日期
                weakSelf.viewModel.fetchTeamResource(date: Date().yp.string("yyyy-MM-dd"))
            }
        }
    }

    /// 更新filter 视图
    func updateFilterViewUI(model: WmcMediaTakePhotoDayModel) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let date = formatter.date(from: model.date)
        formatter.dateFormat = "yyyy年MM月dd日"
        guard let date = date else { return }
        let dateDisplay = formatter.string(from: date)
        filterView.configure(dayModel: dateDisplay)
    }

    /// 获取需要显示的空视图
    func showEmptyOrExampleView(list: [WmcMediaTeamResourceModel]) -> WmcBaseEmptyView {
        /// 只执行一次
        if excuteCount == 0 {
            isFirstPageHasData = list.count > 0
        }
        excuteCount = excuteCount + 1
        if let _: Bool = WmcUserdefault.object(forKey: .Tips.Home.showAblumExampleView) {
            /// 第二次进入已经有值, 只会显示空视图
            return emptyView
        } else {
            /// 第一次进入  首次为空 才显示 示例视图
            if isFirstPageHasData {
                return emptyView
            } else {
                return exmapleView
            }
        }
    }

    private func showCalendarView(dataList: [WmcMediaTakePhotoDayModel]) {
        let selectDateView = WmcCalendarSelectPopView.calendarView()
        selectDateView.photoStatistics = dataList
        selectDateView.show()
        /// 处理日期选择回调
        selectDateView.selectedDateClosure = { [weak self] date in
            guard let weakSelf = self else { return }
            let dateStr = date.yp.string(.iso8601Day, identifier: .asia(.Shanghai))
            /// 模型转换，对象与对象之前交互，模型统一
            var dayModel = WmcMediaTakePhotoDayModel()
            dayModel.date = dateStr
            weakSelf.viewModel.selectedDate = dayModel
            /// filterView 显示的格式
            let dateDisPlay = date.yp.string(.ymd_cn, identifier: .asia(.Shanghai))
            weakSelf.filterView.configure(dayModel: dateDisPlay)
            weakSelf.viewModel.fetchTeamResource(date: dateStr)
        }
        /// 滚到置顶日期所在月份，并选中最近日期
        if let selectedDate = viewModel.selectedDate {
            let date = selectedDate.date.yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)) ?? Date()
            selectDateView.selectedDate = date
            selectDateView.scrollDate(date)
        }
    }

    private lazy var filterView: WmcTeamCloudFilterView = {
        let view = WmcTeamCloudFilterView()
        return view
    }()

    lazy var tableView: UITableView = {
        let view = UITableView()
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcTeamCloudHomeCell.self, forCellReuseIdentifier: "WmcTeamCloudHomeCell")
        view.separatorStyle = .none
        view.isUserInteractionEnabled = true
        /// 空视图代理
        view.emptyDelegate = self
        view.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.getData()
            weakSelf.tableView.mj_header?.endRefreshing()
        })
        return view
    }()

    lazy var emptyView: WmcTeamCloudEmptyView = {
        let view = WmcTeamCloudEmptyView(frame: CGRect(x: 0, y: 0, width: Wmc_screenWidth, height: Wmc_screenHeight))
        return view
    }()

    /// 置顶
    lazy var topButton: WmcNormalButton = {
        let view = WmcNormalButton()
        view.imageView.image = "teamAlbum_home_top_button".wmc_image
        view.contentEdge = .YP.Create(horizontal: 2, vertical: 2)
        view.imgSize = 60
        view.addTarget(self, action: #selector(scrollToTop), for: .touchUpInside)
        return view
    }()

    /// 邀请成员按钮（导航栏）
    lazy var inviteMemberButton: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn(title: "邀请成员", image: "add_team_member".wmc_image)
        btn.setTintColor(.wmc_mainTheme)
        btn.font = 16.wmc_font
        btn.imgSize = 20.wmc_autoHor
        return btn
    }()

    /// 示例
    lazy var exmapleView: WmcTeamExampleView = {
        let view = WmcTeamExampleView(frame: CGRect(x: 0, y: 0, width: Wmc_screenWidth, height: Wmc_screenHeight))
        return view
    }()

    lazy var currentTitleLabel: UILabel = {
        let view = UILabel.YP.Create(font: 22.yp.uiFont(weight: .bold),
                                     color: UIColor.black,
                                     alignment: .left)
        return view
    }()
    
    lazy var netErrorView: WmcBadNetworkEmptyView = {
        let view = WmcBadNetworkEmptyView()
        view.refreshClosure = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
        return view
    }()
}

extension WmcTeamCloudAlbumHomeVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return 1
    }

    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        return viewModel.listData.value.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WmcTeamCloudHomeCell", for: indexPath) as! WmcTeamCloudHomeCell
        let model = viewModel.listData.value[indexPath.row]
        cell.configure(model: model)
        /// 点击图片预览
        cell.clickImage = clickImageBlock()
        /// 点击头像进入详情
        cell.clickAvater = clickAvatarBlock(model: model)
        /// 点击地址回调
        cell.clickLocation = clickLocationBlock(model: model)
        return cell
    }
}

extension WmcTeamCloudAlbumHomeVC {
    /// 点击图片预览回调
    func clickImageBlock() -> ((WmcMediaTeamResourceModel.WmcMediaResourceModel, UIImage?) -> Void)? {
        return { [weak self] model, _ in
            guard let weakSelf = self, let album = weakSelf.viewModel.teamAblum else { return }
            let browser = WmcTeamAlbumBrowser(album: album,
                                              browserDataSource: weakSelf.viewModel.browserDataSource,
                                              originalDataSource: weakSelf.viewModel.originalDataSource)
            browser.browserPhotos(model: model)
        }
    }

    /// 点击头像回调
    func clickAvatarBlock(model: WmcMediaTeamResourceModel) -> (() -> Void)? {
        return { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.getCurrentMember(model: model) { currentMember in
                let vm = WmcTeamCloudMemberDetailVM()
                vm.teamAblum = weakSelf.viewModel.teamAblum
                vm.teamMember = currentMember
                WmcNavigatorManager.push(.teamCloudMemberDetail, parms: vm)?.hidesBottomBarWhenPushed = true
            }
            if model.status == false {
                WmcHudManager.toast("成员已退出")
            }
        }
    }

    /// 生成点击地址回调
    func clickLocationBlock(model: WmcMediaTeamResourceModel) -> (() -> Void)? {
        return {
            let mapAlert = WmcSelectMapAlertView()
            mapAlert.clickClosure = { map in
                if let lat = model.resources.first?.lat, let lon = model.resources.first?.lon {
                    WmcMapManager.openMap(latitude: lat, longitute: lon, name: model.area, mapType: map)
                    YPApp.CurrentVC?.dismiss(animated: true)
                }
            }
            mapAlert.show(model: model)
        }
    }
}

extension WmcTeamCloudAlbumHomeVC {
    /// 滑动到顶部
    @objc func scrollToTop() {
        let topRow = IndexPath(row: 0, section: 0)
        tableView.scrollToRow(at: topRow, at: .top, animated: true)
    }
}

// MARK: - 空视图代理

extension WmcTeamCloudAlbumHomeVC: WmcTableViewEmptyDelegate {
    func tableViewEmpty() -> Int {
        return viewModel.listData.value.count
    }

    func tableViewEmptyView(_: UITableView) -> WmcBaseEmptyView? {
        let list = viewModel.listData.value
        let emptyView = showEmptyOrExampleView(list: list)
        if emptyView.isKind(of: WmcTeamExampleView.classForCoder()) {
            guard let resourceM = viewModel.createExampleData().resources.first else {
                
                return nil }
            exmapleView.bindModel(resourceM.getTransformedModel())
            isShowedExampleView = true
        }
        return emptyView
    }
}
